package cn.wolfcode.wechat.util;

import cn.wolfcode.wechat.vo.AccessTokenVo;
import com.alibaba.fastjson.JSON;

import java.io.InputStream;
import java.util.Properties;

public class AccessTokenUtil {
    private static AccessTokenVo accessTokenVo;
    private static Properties p = new Properties();
    static {
        InputStream in = AccessTokenUtil.class.getClassLoader().getResourceAsStream("wechat.properties");
        try {
            p.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void refeshAccessTokenVo(){
        String appid = p.getProperty("wechat.appId");
        String appsecret = p.getProperty("wechat.appSecret");

        String accessTokenUrl = UrlUtil.ACCESS_TOKEN_URL+"&appid="+appid+"&secret="+appsecret;
        String accessTokenRet = HttpsUtil.get(accessTokenUrl);
        accessTokenVo = JSON.parseObject(accessTokenRet, AccessTokenVo.class);
        accessTokenVo.setCreateTime(System.currentTimeMillis());
    }

    public static String getAccessTokenVo(){
        if(accessTokenVo==null || !accessTokenVo.isAccessTokenValid()){
            refeshAccessTokenVo();
        }
        return accessTokenVo.getAccess_token();
    }
}
